package cn.slipi.pan.web.controller;

import cn.slipi.pan.common.base.BaseController;
import cn.slipi.pan.common.db.DownConfig;
import cn.slipi.pan.common.response.ApiResult;
import cn.slipi.pan.common.util.FileUtil;
import cn.slipi.pan.web.dto.VersionDTO;
import cn.slipi.pan.web.entity.VersionEntity;
import cn.slipi.pan.web.service.VersionService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.io.File;

@Controller
@Mapping("/version")
public class VersionController extends BaseController {

    @Inject
    private DownConfig downConfig;

    @Inject
    private VersionService versionService;

    @Get
    @Mapping("/least")
    public ApiResult<?> least() {
        VersionEntity versionEntity = versionService.getLeast();
        if (versionEntity == null) {
            return fail();
        } else {
            VersionDTO versionDTO = new VersionDTO()
                    .setPower(versionEntity.getPower())
                    .setVersion(versionEntity.getVersion())
                    .setDownUrl(versionEntity.getDownUrl());
            return success(versionDTO);
        }
    }

    @Get
    @Mapping("/download")
    public void download(Context ctx, @Param("version") String version) {
        try {
            String filename = String.format("V%s.zip", version.replaceAll("\\.", ""));
            String filePath = String.format("%s%s%s", downConfig.getDownloadPath(), File.separator, filename);
            File file = new File(filePath);
            ctx.outputAsFile(file);
        } catch (Exception ignored) {
        }
    }
}
